package com.spm.librarianmanagersystem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spm.librarianmanagersystem.mapper.LibrarianMapper;
import com.spm.librarianmanagersystem.mapper.MemberMapper;
import com.spm.librarianmanagersystem.pojo.Librarian;
import com.spm.librarianmanagersystem.pojo.Member;
import com.spm.librarianmanagersystem.service.LoginService;
import com.spm.librarianmanagersystem.utils.Code;
import com.spm.librarianmanagersystem.utils.JsonResult;
import com.spm.librarianmanagersystem.utils.TokenUtil;
import com.spm.librarianmanagersystem.vo.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("LoginService")
public class LoginServiceImpl implements LoginService {
    @Autowired
    private MemberMapper mm;
    @Autowired
    private LibrarianMapper lm;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public String userNormalLogin(JSONObject object) {
        String account = object.getString("account");
        Member memberByID = mm.getMemberByID(account);
        if (memberByID == null) {
            return null;
        }
        String password = object.getString("password");
        String passwordByID = memberByID.getPassword();
        if (!passwordByID.equals(password)) {
            return null;
        } else {
            return TokenUtil.sign(memberByID);
        }
    }

    @Override
    public String userEmailLogin(JSONObject object) {
        String email = object.getString("email");
        Member memberByEmail = mm.getMemberByEmail(email);
        if (memberByEmail == null) {
            return null;
        }
        String code = object.getString("emailcode");
        //从redis中获取相同的验证码
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        String verify = operations.get(email);
        if (!code.equals(verify)) {
            return null;
        } else {
            return TokenUtil.sign(memberByEmail);
        }
    }

    @Value("${spring.mail.username}")
    private String from;
    @Override
    public String send(JSONObject object) {
        String email = object.getString("email");
        Member memberByEmail = mm.getMemberByEmail(email);
        if (memberByEmail == null) {
            return null;
        }
        // 获取随机6位验证码
        String verify = Code.generateVerCode();

        //存储验证码到redis中
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(email, verify, 10, TimeUnit.MINUTES);

        SimpleMailMessage message = new SimpleMailMessage();
        // 发送邮箱
        message.setFrom(from);
        // 接受邮箱
        message.setTo(email);
        // 标题
        message.setSubject("Bookery-书窝 邮箱验证");
        // 内容
        message.setText("尊敬的用户您好：" +
                "您正在进行邮箱验证，本次验证码为：" + verify + "，请在10分钟内进行使用。" +
                "如非本人操作，请忽略此邮件，由此给您带来的不便请谅解");
        try {
            // 发送邮件
            mailSender.send(message);

        } catch (Exception e) {
            return null;
        }
        return "验证码发送成功";
    }

    public JSONObject personTokenLogin(Person p){
        System.out.println(p);
        JSONObject object = new JSONObject();
        object.put("user_id", p.getUserId());
        object.put("id", p.getId());
        object.put("name", p.getName());
        object.put("gender", p.getGender());
        object.put("phone_number", p.getPhoneNumber());
        object.put("avatar", p.getAvatar());
        return object;
    }

    @Override
    public JSONObject userTokenLogin(String id) {
        Member memberByID = mm.getMemberByID(id);
        JSONObject obj = personTokenLogin(memberByID);
        obj.put("role",0);
        return obj;
    }

    @Override
    public String adminNormalLogin(JSONObject object) {
        String account = object.getString("account");
        Librarian librarianByID = lm.getLibrarianByID(account);
        if (librarianByID == null) {
            return null;
        }
        String password = object.getString("password");
        String passwordByID = librarianByID.getPassword();
        if (!passwordByID.equals(password)) {
            return null;
        } else {
            return TokenUtil.sign(librarianByID);
        }
    }

    @Override
    public JSONObject adminTokenLogin(String id) {
        Librarian librarianByID = lm.getLibrarianByID(id);
        JSONObject obj = personTokenLogin(librarianByID);
        obj.put("role",1);
        return obj;
    }
}
